/*
Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
*/

class Solution {
public:
    void do_permute(vector<vector<int> > &res, vector<int> &newnum, vector<int> &num, int cur, int max, vector<int> &used) {
        if (cur == max) {
            res.push_back(newnum);
            return;
        }
        for (int i = 0; i < max; i++) {
            if (used[i]) continue;
            newnum.push_back(num[i]);
            used[i] = 1;
            do_permute(res, newnum, num, cur+1, max, used);
            used[i] = 0;
            newnum.pop_back();
        }
    }
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int> > res;
        if (!num.size()) return res;
        vector<int> newnum;
        vector<int> used(num.size());
        used.clear();
        do_permute(res, newnum, num, 0, num.size(), used);
        return res;
    }
}
